package com.qunar.flight.myserver;

import java.io.IOException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

public class Dispatcher1 implements Dispatcher {
	Selector sel = null;

	public Dispatcher1(Selector sel) throws IOException {
		this.sel = sel;
	}
	Object lock=new Object();
	public void run() {
		for (int count = 1;; count++) {
			try {
				sel.select();// It returns only after at least one channel is
								// selected
				Set<SelectionKey> set = sel.selectedKeys();
				Iterator<SelectionKey> i = set.iterator();
				System.out.println("selected��l����Ϊ��" + set.size());
				for (; i.hasNext();) {
					SelectionKey sk = (SelectionKey) i.next();
					i.remove();
					Handler h = (Handler) sk.attachment();// ��ȡ������
					new Thread(h).start();
				}
				synchronized (lock) {}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void register(SelectableChannel ch, int ops, Handler h)
			throws IOException {
		synchronized (lock) {
			sel.wakeup();
			SelectionKey sk = ch.register(sel, ops, h);
			System.out.println(sk.interestOps() + "***" + ops);
		}
	}
}
